package org.qloudgen.borg.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.qloudgen.borg.beans.Cluster;

public class CommonUtils {

	static Log log = LogFactory.getLog(CommonUtils.class);
	
    /*
     * execShellCommandWithReturn
     */

    public static int execShellCommandWithReturn(final String[] command_org) {
        List<String> command = new ArrayList<String>();
        for (int i = 0; i < command_org.length; i++) {
            command.add(command_org[i]);
        }

        ProcessBuilder process_builder = new ProcessBuilder(command);
        process_builder.redirectErrorStream(true);
        InputStreamReader input_stream_reader = null;

        if (log.isDebugEnabled()){
        	for (int i = 0 ; i < command_org.length; i++){
        		log.debug(command_org[i]);
        	}
        }
        
        try {
            Process process = process_builder.start();
            input_stream_reader = new InputStreamReader(
                    process.getInputStream(), "UTF-8");
            while (true) {
                int c = input_stream_reader.read();
                if (c == -1) {
                    input_stream_reader.close();
                    break;
                }
            }
            process.waitFor();
            int ret = process.exitValue();
            return ret;
        } catch (Exception e) {
        	return -1;
        }
    }

    /*
     * execShellCommandWithReturnLog
     * Execute command_org .
     */

    public static int execShellCommandWithReturnLog(final String[] command_org,StringBuffer sb) {
    	
    	StringBuffer sb1 = new StringBuffer();
   	 	List<String> command = new ArrayList<String>();
        for (int i = 0; i < command_org.length; i++) {
            command.add(command_org[i]);
        }
        
        if (log.isDebugEnabled()){
        	for (int i = 0 ; i < command_org.length; i++){
        		log.debug(command_org[i]);
        	}
        }
        
        ProcessBuilder process_builder = new ProcessBuilder(command);
        process_builder.redirectErrorStream(true);
        InputStreamReader input_stream_reader = null;

        try {
            Process process = process_builder.start();
            input_stream_reader =
                    new InputStreamReader(process.getInputStream(), "UTF-8");
            while (true) {
                int c = input_stream_reader.read();
                if (c == -1) {
                    input_stream_reader.close();
                    break;
                }
                sb1.append(String.valueOf((char) c));
                if (String.valueOf((char) c).equals("\n")){
                    sb.append(sb1.toString());
                    sb1.setLength(0);
                }
                
            }
            process.waitFor();
            log.debug(sb.toString());
            
            int ret = process.exitValue();
            if (ret != 0) {
            	return -1;
            }
        } catch (Exception e) {
           e.printStackTrace();
        }
        return 0;
    }
    
	public final static int writeFileToLocal(String localFile, String content){
		
		BufferedWriter bw = null;
		boolean flag = false;
		try {
			
			bw = new BufferedWriter(new FileWriter(new File(localFile)));
			bw.append(content);
			bw.newLine();
			bw.flush();
			
		} catch (IOException e) {
			e.printStackTrace();
			flag = true;
		} finally {
			try {
				if (bw != null) bw.close();
			} catch (IOException e) {
				e.printStackTrace();
				flag = true;
			}
		}
		if (flag) 
			return -1 ;
		else
			return 0;
	}
	
	public final static String getElement(String str, String delimiter, int index) {
		
		if (str == null || delimiter == null || index < 1) return null;
		
		String[] splits = StringUtils.splitByWholeSeparator(str,delimiter);
		if (splits.length < index) return null;
		
		return splits[index-1];
	}
	
	public final static int scpFilesToClusters(List<Cluster> clusters, List<String> files){
		
		if (clusters.size() == 0)  return 0;
		
		for(Cluster cluster:clusters){
			
			RemoteShellExec remote = new RemoteShellExec(cluster.getMasterIp(),cluster.getSysUser(),cluster.getSysUserPassword());
			try {
				remote.login();
				
				// upload scripts file
				remote.scpFile(files, cluster.getScriptPath());
				remote.close();
				
			} catch (IOException e) {
				log.error(e.getMessage());
				return -1;
			}
							
		}
		return 0;
	}
	
	public final static int execShellOnCluster(Cluster cluster, String cmd){
		

		RemoteShellExec remote = new RemoteShellExec(cluster.getMasterIp(),cluster.getSysUser(),cluster.getSysUserPassword());
		try {
			remote.login();
			
			String result = remote.exec(cmd);
			remote.close();
			
			if (StringUtils.isNotEmpty(result)) return -1;
			
		} catch (IOException e) {
			log.error(e.getMessage());
			return -1;
		}
		
		return 0;
	}

}
